import socket
import urllib.request
from multiprocessing import Process


def get_ip():
    """
    获取本机公网IP地址
    :return:
    """
    my_ip = urllib.request.urlopen('http://ip.42.pl/raw').read()
    return my_ip


def handle_client(res):
    """
    处理客户端请求
    """
    request_data = res.recv(1024)
    # print("request data:", request_data)
    # 构造响应数据
    response_start_line = "HTTP/1.1 200 OK\r\n"
    response_headers = "Server: My server\r\n"
    ip = get_ip()
    ip = str(ip, encoding='utf-8')
    response_body = "<h1>IP: %s </h1>" % ip
    response = response_start_line + response_headers + "\r\n" + response_body

    # 向客户端返回响应数据
    res.send(bytes(response, "utf-8"))

    # 关闭客户端连接
    res.close()


if __name__ == "__main__":
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(("", 8211))
    server_socket.listen(128)

    while True:
        client_socket, client_address = server_socket.accept()
        print("[%s, %s]用户连接上了" % client_address)
        handle_client_process = Process(target=handle_client, args=(client_socket,))
        handle_client_process.start()
        client_socket.close()
